package com.ruoyi.pingjiao.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.pingjiao.domain.Metaclass;
import com.ruoyi.pingjiao.domain.vo.EvaluationActivityVo;
import com.ruoyi.pingjiao.mapper.MetaclassMapper;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.pingjiao.mapper.StudentMapper;
import com.ruoyi.pingjiao.domain.Student;
import com.ruoyi.pingjiao.service.IStudentService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 学生管理Service业务层处理
 *
 * @author 胡浩鹏
 * @date 2022-10-15
 */
@Service
@Slf4j
public class StudentServiceImpl implements IStudentService
{
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private SysUserRoleMapper userRoleMapper;
    @Autowired
    private SysRoleMapper roleMapper;
    @Autowired
    private MetaclassMapper metaclassMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    /**
     * 查询学生管理
     *
     * @param studentId 学生管理主键
     * @return 学生管理
     */
    @Override
    public Student selectStudentByStudentId(Long studentId)
    {
        return studentMapper.selectStudentByStudentId(studentId);
    }

    /**
     * 查询学生管理列表
     *
     * @param student 学生管理
     * @return 学生管理
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<Student> selectStudentList(Student student)
    {
        return studentMapper.selectStudentList(student);
    }

    /**
     * 新增学生管理
     *
     * @param student 学生管理
     * @return 结果
     */
    @Transactional
    @Override
    public int insertStudent(Student student)
    {
        student.setCreateTime(DateUtils.getNowDate());
        int i = studentMapper.insertStudent(student);

        SysUser user = new SysUser();
        user.setNickName(student.getRealName());
        user.setDeptId(student.getDeptId());
        user.setSex(student.getGender());
        user.setStuOrTeaId(student.getStudentId());
        user.setUserName(student.getStudentNo());
        user.setPassword(SecurityUtils.encryptPassword("123456"));

        userMapper.insertUser(user);

        SysRole role = new SysRole();
        role.setRoleName("学生");
        List<SysRole> sysRoles = roleMapper.selectRoleList(role);

        List<SysUserRole> list = new ArrayList<SysUserRole>();
        SysUserRole ur = new SysUserRole();
        ur.setUserId(user.getUserId());
        ur.setRoleId(sysRoles.get(0).getRoleId());
        list.add(ur);
        userRoleMapper.batchUserRole(list);

        student.setUserId(user.getUserId());
        studentMapper.updateStudent(student);

        return i;
    }

    /**
     * 修改学生管理
     *
     * @param student 学生管理
     * @return 结果
     */
    @Override
    public int updateStudent(Student student)
    {
        student.setUpdateTime(DateUtils.getNowDate());
        return studentMapper.updateStudent(student);
    }

    /**
     * 批量删除学生管理
     *
     * @param studentIds 需要删除的学生管理主键
     * @return 结果
     */
    @Override
    public int deleteStudentByStudentIds(Long[] studentIds)
    {
        return studentMapper.deleteStudentByStudentIds(studentIds);
    }

    /**
     * 删除学生管理信息
     *
     * @param studentId 学生管理主键
     * @return 结果
     */
    @Override
    public int deleteStudentByStudentId(Long studentId)
    {
        return studentMapper.deleteStudentByStudentId(studentId);
    }
    /**
     * 根据学号获取学生信息
     * @author  hpf
     * @param  studentNo 学号
     * @return 教师
     */
    @Override
    public Student selectStudentByNo(String  studentNo){  return  studentMapper.selectStudentByNo(studentNo);  }


    /**
     * 根据学生id获取上课、教师信息
     * @author  hpf
     *     *
     * @return
     */
    @Override
    public List<EvaluationActivityVo> selectTeacherListByStudentId(Long studentId,Long activityId){
        Map<String,Object> map =new HashMap<String,Object>();
        map.put("studentId",studentId);
        map.put("activityId",activityId);
        return  studentMapper.selectTeacherListByStudentId(map);
    }

    @Override
    public Student getStudentInfo(Long userId) {
        return studentMapper.getStudentInfo(userId);
    }

    /**
     * 批量导入学生 Excel
     * @param studentList 学生集合
     * @param operName 操作人
     * @return
     */
    @Override
    public String importStudent(List<Student> studentList, String operName) {
        if (StringUtils.isNull(studentList) || studentList.isEmpty()) {
            throw new ServiceException("导入学生数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (Student student : studentList) {

            try {
                Metaclass metaclass = metaclassMapper.selectMetaclassByMetaclassName(student.getMetaclassName());

                // 根据学号查询学生
                Student stuResult2 = studentMapper.selectStudentByStudentNo(student.getStudentNo());


                if (StringUtils.isNull(stuResult2) && !StringUtils.isNull(metaclass) ) {
                    student.setDeptId(metaclass.getDeptId());
                    student.setMeataclassId(metaclass.getMeataclassId());
                    student.setGrade(metaclass.getGrade());
//                    student.setProfessionId(metaclass.getProfessionId());
                    // 不存在
                    // 插入 学生
                    SysUser sysUser = randomStudentUser(student);
                    student.setCreateBy(SecurityUtils.getUsername());
                    student.setUserId(sysUser.getUserId());
                    student.setCreateTime(DateUtils.getNowDate());
                    studentMapper.insertStudent(student);
                    SysUserRole sysUserRole=new SysUserRole();
                    sysUserRole.setRoleId(Long.valueOf(107));
                    sysUserRole.setUserId(sysUser.getUserId());
                    sysUserRoleMapper.insert(sysUserRole);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、学生 " + student.getRealName() + " 导入成功");
                } else if (!StringUtils.isNull(stuResult2) && !StringUtils.isNull(metaclass) ) {
                    // 存在  不支持更新
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、学生 " + student.getRealName() + "学号已存在");
                } else {
                    // 存在  不支持更新
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、学生 " + student.getRealName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、学生 " + student.getRealName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }

        }
        if (failureNum > 0) {
            failureMsg.insert(0, "共 " + failureNum + " 条数据格式不正确并导入失败，错误如下：");
        }
        if (successNum > 0) {
            successMsg.insert(0, "共 " + successNum + " 条导入成功，数据如下：");
        }
        return successMsg.toString() + "<br/>" + failureMsg.toString();
    }

    private SysUser randomStudentUser(Student student) {
        // 给学生分配用户
        SysUser sysUser = new SysUser();
        sysUser.setUserName(student.getStudentNo());
        sysUser.setPassword(SecurityUtils.encryptPassword(student.getStudentNo()));
        sysUser.setNickName(student.getRealName());
        sysUser.setRemark("学生");
//        sysUser.setPhonenumber(teacher.get());
        sysUser.setDeptId(student.getDeptId());
        if ("男".equals(student.getGender())) {
            sysUser.setSex("0");
        } else if ("女".equals(student.getGender())) {
            sysUser.setSex("1");
        } else {
            sysUser.setSex("2");
        }
        sysUser.setCreateBy(SecurityUtils.getLoginUser().getUsername());
        userMapper.insertUser(sysUser);
        // 查询刚插入的用户
        return userMapper.selectUserByUserName(student.getStudentNo());
    }


    /**
     * 根据userid获取studentId
     * @author  hpf
     *     *
     */
    @Override
    public Long selectStudentIdByUserId(Long userId){return  studentMapper.selectStudentIdByUserId(userId);}

}
